<?php

class BasketItemsController extends AppController {

  var $name = "BasketItems";
  
  var $helpers = array('Html','Image');
  
  function del($id) {
    if(!$this->checkSession()) {
      $this->forceLogin();
    }
    $b = $this->BasketItem->find('BasketItem.id = "' . $id . '"',null,null,2);
    $this->BasketItem->Orderable->id = $b['Orderable']['id'];
    $this->BasketItem->Orderable->saveField('inventory_left', $b['Orderable']['inventory_left'] + $b['BasketItem']['quantity']);
    $this->BasketItem->del($id);
    $this->Session->setFlash('That item has been removed from your basket.','message_ok');
    if ($this->Session->check('check-in')) {
    	$this->redirect('/producers/checkIn/' . $this->Session->read('check-in'));
    	exit();
    }
    $this->redirect('/members/basket');
  }
  
  function markMissing($id) {
    if (!$this->checkSession()) {
      $this->forceLogin();
    } else {
      if($this->checkLevel(AUTH_CASH)) { // must be administrator
      } else {
        $this->notAuth();
      }
    }
    $this->BasketItem->id = $id;
    $this->BasketItem->saveField('missing',1);
    if ($this->Session->check('check-in')) {
    	$this->redirect('/producers/checkIn/' . $this->Session->read('check-in'));
    	exit();
    }
    if ($this->Session->check('current_basket')) {
    	$this->redirect('/members/basket');
    	exit();
    }
    $this->redirect('/members/menu');
  }
  
  function markDelivered($id) {
    if (!$this->checkSession()) {
      $this->forceLogin();
    } else {
      if($this->checkLevel(AUTH_CASH)) { // must be administrator
      } else {
        $this->notAuth();
      }
    }
    $this->BasketItem->id = $id;
    $this->BasketItem->saveField('missing',0);
    if ($this->Session->check('check-in')) {
    	$this->redirect('/producers/checkIn/' . $this->Session->read('check-in'));
    	exit();
    }
    if ($this->Session->check('current_basket')) {
    	$this->redirect('/members/basket');
    	exit();
    }
    $this->redirect('/members/menu');
   // exit();
  }
  
  function edit($id) {
    if(!$this->checkSession()) {
      $this->forceLogin();
    }
    $b = $this->BasketItem->find('BasketItem.id = "' . $id . '"',null,null,2);
    if (!empty($this->data)) {
      $difference = ($this->data['BasketItem']['quantity'] - $b['BasketItem']['quantity']);
      if ($difference > 0) {
        //make sure there's enough
        if (!($b['Orderable']['inventory_start'] == 0)) {
          if ($b['Orderable']['inventory_left'] < $difference) {
            $this->Session->setFlash("There is not enough of that item to order that many.");
            $this->redirect('/members/basket');
          }
        }
      }
      if ($this->data['BasketItem']['quantity'] == 0) {
        $this->BasketItem->del($id);
        $this->BasketItem->Orderable->id = $b['Orderable']['id'];
        $this->BasketItem->Orderable->saveField('inventory_left', $b['Orderable']['inventory_left'] - $difference);
        $this->Session->setFlash("Item Removed from Basket");
        $this->redirect('/members/basket');
      }
      if(!$this->BasketItem->save($this->data)) {
        //error
      } else {
        $this->BasketItem->Orderable->id = $b['Orderable']['id'];
        $this->BasketItem->Orderable->saveField('inventory_left', $b['Orderable']['inventory_left'] - $difference);
        $this->Session->setFlash('Item Quantity Updated');
        $this->redirect('/members/basket');
      }
    }
    $this->set('item',$b);
    $product = $this->BasketItem->Orderable->find('Product.product_id = "' . $b['Orderable']['product_id'] . '"', null, null, 2);
    App::import('Model', 'Producer');
    $producer = new Producer();
    $product['Producer']['business_name'] = $producer->businessName($product['Product']['producer_id']);
    $this->set('product',$product);
    $this->data = $this->BasketItem->findById($id);
  }
  
  function showAll($sort=null, $page = 1) {
    if (!$this->checkSession()) {
      $this->forceLogin();
    } else {
      if($this->checkLevel(AUTH_ADMIN) || $this->checkLevel(AUTH_CASH)) { // must be administrator
      } else {
        $this->notAuth();
      }
    }
    
    $delId = Configure::read('Delivery.delivery_id');
    
    if (!empty($this->params['named'])) {
    	if (isset($this->params['named']['delivery'])) {
    		$delId = $this->params['named']['delivery'];
    	}
    }
		
		$d = new Delivery();
		$delivery = $d->find('first', array('conditions' => array('delivery_id' => $delId)));
		$neighbors = $d->find('neighbors', array("recursive" => -1, 'field'=>'Delivery.order_open', 'value' => $delivery['Delivery']['order_open']));
		
    if (is_null($sort)) {
      $sort = "producer";
    }
    if ($sort == "producer") {
			$sorting = array(array('producer','business_name'),array('member','last_name'));
			$number = 10;
    } else if ($sort == "member") {
			$sorting = array(array('member','last_name'),array('producer','business_name'));
			$number = 50;
    }
		
		$order = $sorting[0][0] . ' . ' . $sorting[0][1] . ' , ' . $sorting[1][0] . ' . ' . $sorting[1][1];
		$order = str_replace('member . last_name', 'member . last_name , member . first_name', $order);
		if ($delivery['Delivery']['open']) {
    	$lines = $this->BasketItem->c_find(null, $sort, $delId, $page, $number);
		} else {
			$lines = array();
		}
    $this->set(compact('sorting', 'lines', 'page', 'neighbors', 'delivery'));
  }
  
  function stats($what = null) {
  	$this->layout = 'ajax';
  	$d = new Delivery();
  	$deliveries = $d->findAll('`special_order` = 0 AND `order_open`>=\'' . date('Y-m-d',time()-6*30*24*60*60) . '\'', null, 'Delivery.order_open ASC');
  	$b = new BasketItem();
  	$type = 'line';
  	$special = '';
  	if ($what == 'number') {
  		$n = array('Baskets');
  		$type = 'column';
  	} else if ($what == 'average') {
  		$n = array('Average Basket');
  		$special = '$';
  	} else {
  		$n = array('Total Sales');
  		$special = '$';
  	}
  	$p = array('Pickup Dates');
  	foreach($deliveries as $del) {
  		if ($what == 'number') { $n[] = $b->numBaskets($del['Delivery']['delivery_id']); }
  		else if ($what == 'average') { $n[] = $b->avgBasketTotal($del['Delivery']['delivery_id']); }
  		else { $n[] = $this->BasketItem->basketsTotal($del['Delivery']['delivery_id']); }
  		preg_match("/\d{2}(\d{2})-(\d{2})-(\d{2})/", $del['Delivery']['pickup_open'], $date);
  		$p[] = $date[2] . "/" . $date[3];
  	}
  	$this->set('pickups', $p);
  	$this->set('data', $n);
  	$this->set('type', $type);
  	$this->set('special', $special);
  }
  
  function dayStats() {
  	$this->layout = 'ajax';
  	$stats = $this->BasketItem->basketsTotalByDay();
  	$p = array_keys($stats);
  	$n = array_values($stats);
  	array_unshift($p,"Sales By Day");
  	array_unshift($n,null);
  	$this->set('pickups',$p);
  	$this->set('data',$n);
  	$type = 'line';
  	$special = '$';
  	$this->set('type', $type);
  	$this->set('special', $special);
  }
  
  function add() {
  	$this->mustBe(AUTH_CASH);
  	$member_id = ($this->Session->check('current_basket')) ? $this->Session->read('current_basket') : $this->userInfo['member_id'];
  	if (empty($this->data)) {
  		$this->Session->setFlash('Nothing added - there was no data to create a new basket item!');
  	} else {
  		$bItem = array(
  			'BasketItem' => array(
  				'member_id' => $member_id,
  				'quantity' => $this->data['BasketItem']['quantity'],
  				'weight' => $this->data['BasketItem']['weight']
  			)
  		);
  		$o = new Orderable();
  		if ($this->data['Product']['product_id'] != 0) {
  			//current, extant orderable
  			$orderable = $o->c_find('Product.product_id = ' . $this->data['Product']['product_id'] . ' AND Orderable.delivery_id = ' . $this->deliveryId);
  			$orderable = $orderable[0];
  		} else {
  			//we need to create or look up the "other" orderable
  			$orderable = $o->c_find('Product.product_name = "Other" AND Product.producer_id = "' . $this->data['Producer']['producer_id'] . '" AND Orderable.delivery_id = ' . $this->deliveryId);
  			if (empty($orderable)) {
  				//there's no "Other" orderable for this cycle yet.  Look for "Other" product
  				$p = new Product();
  				$product = $p->find('first', array('conditions'=>array('Product.product_name' => 'Other', 'Product.producer_id' => $this->data['Producer']['producer_id'])));
  				if (empty($product)) {
  					//there is no "Other" product for this producer yet.
  					$other_prod = array(
  						'Product'=> array(
  							'product_name' => 'Other',
  							'archived' => 1,
  							'detailed_notes' => 'This is an add-on product sold at drop-off.',
  							'random_weight' => 1,
  							'unit_price' => 1,
  							'pricing_unit' => 'dollar',
  							'ordering_unit' => 'item',
  							'producer_id' => $this->data['Producer']['producer_id'],
  							'donotlist' => 1,
  							'tax_exempt' => 1
  						)
  					);
  					$p->save($other_prod);
  					$product = $p->findByProductId($p->getLastInsertId());
  				}
  				$o->addForProduct($product);
  				$orderable = $o->findById($o->getLastInsertId());
  			} else {
  				$orderable = $orderable[0];
  			}
  		}
  		$bItem['BasketItem']['orderable_id'] = $orderable['Orderable']['id'];
  		$this->BasketItem->save($bItem);
  		$this->Session->setFlash('Item Added!', 'message_ok');
  		$this->redirect('/members/basket');
  	}
  }
  
}
?>